<template>
	<view>
		<view class="cgList">
			<text @click="changeProject(item, index)" :class="isActive == index ? 'active' : ''"
				v-for="(item, index) in projectList" :key="item.id">{{ item.projectName }}</text>
		</view>

		<view class="autoHeightBox">
			<!-- 日期选择 -->
			<lxCalendar @change="change" :startTime="nowTime" :endTime="overTime"></lxCalendar>
			<view>
				<view class="labelline">
					<text class="label1">已选择</text>
					<text class="label2">可订</text>
				</view>
				<!-- <zb-table :show-header="true"></zb-table> -->
				<view class="tableroom">
					<view class="timetable">
						<view v-for="(t, index) in busList" :key="index">{{ t }}</view>
					</view>
					<view class="righttable">
						<view class="righttableauto">
							<view class="cdtable">
								<view v-for="c in czList" :key="c.id">{{ c.name }}</view>
							</view>
							<view class="bodytable">
								<checkbox-group @change="radioChange" class="mainClick">
									<view class="lie" v-for="(c, pIndex) in priceTable" :key="c.id">
										<view v-for="(item, index) in c.prices" :key="index"
											:class="item.expired || item.locked || item.linkage ? 'dis' : ''">
											<checkbox :value="setCheckBoxVal(pIndex, index)" class="cc"
												:checked="item.checked"
												:disabled="item.expired || item.locked || item.linkage" />
											<!-- <label class="radio" v-if="item.expired">过期</label> -->
											<label class="radio lockedlocked" v-if="item.locked&&item.orderType=='3'">
												<!-- 锁场 -->
												<image class="lockIcon" src="/static/lockIcon.png" />
											</label>
											<label class="radio locked"
												v-else-if="item.locked&&item.orderType!='3'">已售</label>
											<label class="radio" v-else>￥{{ item.price }}</label>
										</view>
									</view>
								</checkbox-group>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="bbfix">
			<!-- 底部提交 -->
			<view class="price">
				合计：
				<text>￥{{ money }}</text>
			</view>
			<view class="chooseNum" @click="popChoose">{{ choseList.length }}个场次</view>
			<view class="subBtn" @click="goBooking">提交</view>
		</view>
		<!-- <uni-calendar ref="calendar" :insert="false" @confirm="confirm" /> -->

		<uni-popup ref="popup" background-color="#fff" type="bottom">
			<view class="popup-content ccitemBox">
				<view class="ccitem" v-for="(c, index) in choseList" :key="index">
					{{ c.name }}
					<icon type="cancel" size="26" @click="delChose(c)" />
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import lxCalendar from '@/components/lx-calendar/lx-calendar.vue';
	import {
		nextTick,
		ref
	} from 'vue';
	import {
		onLoad,onShow
	} from '@dcloudio/uni-app';
	import _ from 'lodash';
	import dayjs from 'dayjs';
	import * as api from '@/common/api.js';

	const app = getApp();
	const projectList = ref([]);
	const priceTable = ref([]);
	const czList = ref([]);
	const isActive = ref(0);
	const popup = ref(null);
	const calendar = ref(null);
	// const card = ref(null);

	const busList = ref([]);
	const money = ref(0);
	const choseList = ref([]);
	const overTime = ref(0);
	const nowTime = dayjs(dayjs().format('YYYY-MM-DD')).valueOf();

	let timeList = [
		'00:00',
		'00:30',
		'01:00',
		'01:30',
		'02:00',
		'02:30',
		'03:00',
		'03:30',
		'04:00',
		'04:30',
		'05:00',
		'05:30',
		'06:00',
		'06:30',
		'07:00',
		'07:30',
		'08:00',
		'08:30',
		'09:00',
		'09:30',
		'10:00',
		'10:30',
		'11:00',
		'11:30',
		'12:00',
		'12:30',
		'13:00',
		'13:30',
		'14:00',
		'14:30',
		'15:00',
		'15:30',
		'16:00',
		'16:30',
		'17:00',
		'17:30',
		'18:00',
		'18:30',
		'19:00',
		'19:30',
		'20:00',
		'20:30',
		'21:00',
		'21:30',
		'22:00',
		'22:30',
		'23:00',
		'23:30'
	];
	let startBus,
		endBus,
		projectId,
		halfHourAllow,
		orderDate,
		getData = null;
	let dayOver = false;

	const change = e => {
		if (e) {
			orderDate = e.fulldate;
			api.getSiteList(projectId).then(res => {
				czList.value = res.data;
				uni.hideLoading();
			});
		}
		if (orderDate && overTime.value != 0) {
			dayOver = dayjs(orderDate).valueOf() >= overTime.value;
		}

		if (getData) {
			getData();
		}
	};
	const currUser = uni.getStorageSync('currUser');
	onShow(() => {
		if (app.globalData.isLogin) {
				projectList.value = app.globalData.venue.projectList;
				changeProject(projectList.value[0], 0);
		} else {
			app.firstLoadCallback = () => {
				projectList.value = app.globalData.venue.projectList;
				changeProject(projectList.value[0], 0);
			};
		}
	});
	function checkCanOrderDays() {
		let od;
		// app.globalData.relateProjectIdList
		if (app.globalData.isVip) {
			if (app.globalData.relateVenueProjectIdList.length == 0) {
				// 所有项目
				od = app.globalData.venueConfig.memberOverDay;
			} else if (app.globalData.relateVenueProjectIdList.indexOf(projectId) > -1) {
				od = app.globalData.venueConfig.memberOverDay;
			} else {
				od = app.globalData.venueConfig.normalOverDay;
			}
		} else {
			od = app.globalData.venueConfig.normalOverDay;
		}
		if (od > -1) {
			// console.log(od,dayjs(nowTime).add(od, 'day'))
			overTime.value = dayjs(nowTime).add(od, 'day').valueOf();
		}
		console.log(od,overTime.value)
	}
	
	// 预定类型 0 普通预定 1长租预定 2 预留 3 锁场 orderType
	const setCheckBoxVal = (pIndex, index) => {
		let siteId = priceTable.value[pIndex].id;
		let siteName = priceTable.value[pIndex].name;
		let price = priceTable.value[pIndex].prices[index].price;
		let bus = busList.value[index];
		return `${siteId},${siteName},${price},${bus},${index},${orderDate}`;
	};

	function changeProject(item, index) {
		isActive.value = index;
		projectId = item?.id || 0;
		checkCanOrderDays();
		
		halfHourAllow = item.halfHourAllow;
		startBus = item.businessStart;
		endBus = item.businessEnd;

		let startBusStr = startBus.replace(/:/g, '');
		let endBusStr = endBus.replace(/:/g, '');

		busList.value = [];
		_.forEach(timeList, (t, i) => {
			if (t.replace(/:/g, '') >= startBusStr && t.replace(/:/g, '') < endBusStr) {
				if (item.halfHourAllow == '1') {
					busList.value.push(t);
				} else {
					if (i % 2 == 0) {
						busList.value.push(t);
					}
				}
			}
		});

		uni.showLoading({
			title: '加载中'
		});

		api.getSiteList(projectId).then(res => {
			czList.value = res.data;

			if (!getData) {
				getData = () => {
					getPrice();
				};
			}

			change();
			uni.hideLoading();
		});

		choseList.value = [];
		money.value = 0;
	}
	//不在预定时间内
	function checkExpired(priceTime) {
		if (dayOver) {
			return true;
		}
		let now
		if(halfHourAllow == '1'){
			now = dayjs().add(-30, 'minute').valueOf();
		}else{
			now = dayjs().add(-60, 'minute').valueOf();
		}
		
		if (now > priceTime) {
			return true;
		}
		let startTime, endTime;
		// if (app.globalData.isVip && projectId == app.globalData.relateProjectId) {
		// 	startTime = dayjs(`${orderDate} ${app.globalData.venueConfig.memberPeriodStart}`).valueOf();
		// 	endTime = dayjs(`${orderDate} ${app.globalData.venueConfig.memberPeriodEnd}`).valueOf();
		// } else {
		// 	startTime = dayjs(`${orderDate} ${app.globalData.venueConfig.normalPeriodStart}`).valueOf();
		// 	endTime = dayjs(`${orderDate} ${app.globalData.venueConfig.normalPeriodEnd}`).valueOf();
		// }

		if (app.globalData.isVip) {
			if (app.globalData.relateVenueProjectIdList.length == 0) {
				// 所有项目
				startTime = dayjs(`${orderDate} ${app.globalData.venueConfig.memberPeriodStart}`).valueOf();
				endTime = dayjs(`${orderDate} ${app.globalData.venueConfig.memberPeriodEnd}`).valueOf();
			} else if (app.globalData.relateVenueProjectIdList.indexOf(projectId) > -1) {
				startTime = dayjs(`${orderDate} ${app.globalData.venueConfig.memberPeriodStart}`).valueOf();
				endTime = dayjs(`${orderDate} ${app.globalData.venueConfig.memberPeriodEnd}`).valueOf();
			} else {
				startTime = dayjs(`${orderDate} ${app.globalData.venueConfig.normalPeriodStart}`).valueOf();
				endTime = dayjs(`${orderDate} ${app.globalData.venueConfig.normalPeriodEnd}`).valueOf();
			}
		} else {
			startTime = dayjs(`${orderDate} ${app.globalData.venueConfig.normalPeriodStart}`).valueOf();
			endTime = dayjs(`${orderDate} ${app.globalData.venueConfig.normalPeriodEnd}`).valueOf();
		}

		return priceTime < startTime || priceTime >= endTime;
	}

	function getPrice() {
		if (!orderDate) {
			return;
		}
		uni.showLoading({
			title: '加载中'
		});
		priceTable.value = [];
		Promise.all([
			api.maGetPrice({
				projectId: projectId,
				orderDate: orderDate
			}),
			api.getDateOrderInfo({
				projectId: projectId,
				orderDate: orderDate
			})
		]).then(res => {
			priceTable.value = [];
			_.forEach(czList.value, c => {
				let prices = [];
				let siteOrder = res[1].data[c.id];
				_.forEach(siteOrder, o => {
					o.startTime = dayjs(`${o.orderDate} ${o.orderTimePeriod.split(',')[0]}`)
						.valueOf();
					o.endTime = dayjs(`${o.orderDate} ${o.orderTimePeriod.split(',')[1]}`)
					.valueOf();
				});

				_.forEach(res[0].data[c.id], (p, i) => {
					let priceTime = dayjs(`${orderDate} ${busList.value[i]}`).valueOf();
					let status = getOrderType(siteOrder, priceTime);

					prices.push({
						price: p,
						expired: checkExpired(priceTime),
						locked: status.locked,
						orderType: status.orderType,
						checked: _.some(choseList.value, choose => {
							let temp = choose.value.split(',');
							if (c.id == temp[0] && orderDate == temp[5] && i ==
								temp[4]) {
								return true;
							} else {
								return false;
							}
						}),
						linkage: false
					});
				});

				priceTable.value.push({
					id: c.id,
					name: c.name,
					prices: prices
				});
			});

			checkLinkage();
			uni.hideLoading();
		});
	}

	function getOrderType(siteOrder, priceTime) {
		let priceTimeEnd;
		if(halfHourAllow == '1'){
			priceTimeEnd = dayjs(priceTime).add(30, 'minute').valueOf();
		}else{
			priceTimeEnd = dayjs(priceTime).add(60, 'minute').valueOf();
		}
		
		let order = _.find(siteOrder, o => {
			return (priceTime >= o.startTime && priceTime < o.endTime) || (priceTimeEnd > o.startTime && priceTimeEnd <= o.endTime) ;
		})

		return order ? {
			locked: true,
			orderType: order.orderType
		} : {
			locked: false,
			orderType: '-1'
		}
	}
	/**
	 * 场地联动检测
	 */
	function checkLinkage() {
		_.forEach(priceTable.value, t => {
			_.forEach(t.prices, p => {
				p.linkage = false;
			});
		});

		_.forEach(priceTable.value, t => {
			_.forEach(t.prices, (p, index) => {
				if ((p.locked || p.checked) && !p.linkage) {
					setLinkage(t.id, index);
				}
			});
		});
	}

	/**
	 * 设置联动
	 * @param {Object} siteId
	 * @param {Object} busIndex
	 */
	function setLinkage(siteId, busIndex) {
		let currSite = _.find(czList.value, s => s.id == siteId);

		// 是父级场地找对应的子场地
		if (currSite.parentId == 0) {
			const childSites = _.filter(czList.value, s => {
				return s.parentId == currSite.id;
			});
			if (childSites.length > 0) {
				_.each(childSites, s => {
					let childPriceTable = _.find(priceTable.value, p => p.id == s.id);
					childPriceTable.prices[busIndex].linkage = true;
				});
			}
		}
		// 是子场地找对应的父级场地
		else {
			const parentSite = _.find(czList.value, s => {
				return s.id == currSite.parentId;
			});
			let parentPriceTable = _.find(priceTable.value, p => p.id == parentSite.id);
			parentPriceTable.prices[busIndex].linkage = true;
		}
	}

	function openCalendar() {
		calendar.value.open();
	}

	function radioChange(evt) {
		_.remove(choseList.value, c => {
			let temp = c.value.split(',');
			return temp[5] == orderDate;
		});

		_.forEach(priceTable.value, p => {
			_.forEach(p.prices, pp => {
				pp.checked = false;
			});
		});

		_.forEach(evt.detail.value, e => {
			let temp = e.split(',');

			_.find(priceTable.value, p => {
				if (p.id == temp[0]) {
					p.prices[temp[4]].checked = true;
					return true;
				}
			});

			choseList.value.push({
				value: e,
				id: temp[0],
				date: temp[5],
				index: temp[4],
				halfHourAllow: halfHourAllow,
				name: `${temp[1]} -- ${temp[5].substr(5)} ${temp[3]} -- ￥${temp[2]}`
			});
		});
		money.value = _.reduce(
			choseList.value,
			(sum, c) => {
				return sum + parseFloat(c.value.split(',')[2]);
			},
			0
		).toFixed(2);

		checkLinkage();
	}

	function goBooking() {
		if (choseList.value.length == 0) {
			return;
		}

		uni.showModal({
			content: '确定提交订单？',
			success: function(res) {
				if (res.confirm) {
					uni.showLoading({
						title: '订单提交中...'
					});

					let project = _.find(projectList.value, p => p.id == projectId);

					choseListOrderBy();

					let orderList = [];
					_.forEach(choseList.value, c => {
						let temp = c.value.split(',');
						let start = temp[3];
						let end;
						if (halfHourAllow == '1') {
							end = dayjs(`${c.date} ${start}`)
								.add(30, 'minute')
								.format('HH:mm');
						} else {
							end = dayjs(`${c.date} ${start}`)
								.add(1, 'hour')
								.format('HH:mm');
						}

						c.projectName = project.projectName;
						c.siteName = temp[1];
						c.price = temp[2];
						c.orderTime = `${start},${end}`;
						orderList.push({
							siteId: c.id,
							orderDate: c.date,
							orderTime: c.orderTime
						});
					});
					api.maReserveVenueWithInfoList({
						orderInfoList: JSON.stringify(orderList),
						finalPrice: money.value + ''
					}).then(res => {
						uni.hideLoading();
						if (choseList.value.length == 0) {
							return;
						}

						let data = res.data;
						uni.navigateTo({
							url: '/pages/index/booking',
							events: {
								acceptDataFromOpenedPage: () => {
									choseList.value = [];
									money.value = 0;
									change();
								}
							},
							success: function(res) {
								res.eventChannel.emit('acceptDataFromOpenerPage', {
									orderInfo: choseList.value,
									order: data
								});
							}
						});
					});
				}
			}
		});
	}

	function popChoose() {
		if (choseList.value.length > 0) {
			choseListOrderBy();
			popup.value.open();
		}
	}

	function choseListOrderBy() {
		choseList.value = _.orderBy(choseList.value, ['date', 'id', 'index']);
	}

	function delChose(c) {
		let temp = c.value.split(',');
		if (orderDate == temp[5]) {
			_.find(priceTable.value, p => {
				if (p.id == temp[0]) {
					p.prices[temp[4]].checked = false;
					return true;
				}
			});
		}
		_.pull(choseList.value, c);
		money.value = _.reduce(
			choseList.value,
			(sum, c) => {
				return sum + parseFloat(c.value.split(',')[2]);
			},
			0
		).toFixed(2);

		//场地联动
		checkLinkage();

		if (choseList.value.length == 0) {
			popup.value.close();
		}
	}
</script>

<style lang="scss">
	.timetable {
		width: 120rpx;
		padding-top: 70rpx;
		box-shadow: 0 3rpx 20rpx 0 rgba(77, 77, 77, 0.28);
		z-index: 2;
		background: #fff;
		min-height: calc(100vh - 500rpx);
		position: sticky;
		left: 0;
	}

	.timetable view {
		line-height: 70rpx;
		height: 70rpx;
		text-align: center;
		margin: 10rpx 0 0;
		font-size: 24rpx;
		border: 1rpx solid #fff;
		color: #000000;
	}

	.cdtable {
		background: #fff;
		position: sticky;
		position: -webkit-sticky;
		top: 0;
		display: flex;
		height: 70rpx;
		flex-wrap: nowrap;
		z-index: 1;
	}

	.cdtable view {
		font-size: 24rpx;
		line-height: 70rpx;
		width: 170rpx;
		text-align: center;
	}

	.bodytable {
		background: #f7f8fa;
	}

	.mainClick {
		display: flex;
		flex-wrap: nowrap;
	}

	.mainClick .lie view {
		position: relative;
		box-sizing: border-box;
		border: 1rpx solid #ff8124;
		width: 150rpx;
		margin: 10rpx 10rpx 0;
		color: #ff8124;
		font-size: 28rpx;
		line-height: 70rpx;
		background: #ffffff;
		text-align: center;
	}

	.mainClick .lie .cc {
		opacity: 0;
		position: absolute;
		width: 100%;
		height: 100%;
		left: 0;
		top: 0;
	}

	.mainClick .lie label {
		padding: 0;
		display: block;
		height: 100%;
		width: 100%;
	}

	.mainClick .lie label.locked {
		background: #ddd;
	}

	.mainClick .lie label.lockedlocked {
		/* border: 1rpx solid #e1e1e1; */

		image {
			width: 30rpx;
			height: 37rpx;
			position: relative;
			top: 6rpx;
		}
	}

	.mainClick .lie .cc[checked]+label {
		color: #fff;
		background: #ff8124;
	}

	.mainClick .lie view.dis {
		color: #b3b3b3;
		border: 1rpx solid #fff;
	}

	.tableroom {
		height: calc(100vh - 530rpx);
		overflow: auto;
		position: relative;
		border-top: 1rpx solid #dcdcdc;
	}

	.righttable {
		height: 100%;
		width: 630rpx;
		/* overflow: auto; */
		position: absolute;
		top: 0;
		left: 120rpx;
	}

	.righttableauto {
		position: absolute;
		background: #f7f8fa;
		height: 100%;
		min-width: 100%;
	}

	.cgList {
		background: #fff;
		overflow: auto;
		padding: 26rpx;
	}

	.cgList text {
		padding: 3rpx 26rpx;
		text-align: center;
		background: #ffffff;
		border-radius: 27rpx;
		font-size: 28rpx;
		color: #000000;
		margin-right: 30rpx;
		box-shadow: 0px 3rpx 21rpx 0px rgba(236, 236, 236, 0.63);
		line-height: 54rpx;
		float: left;
		display: block;
	}

	.cgList text.active {
		background: linear-gradient(270deg, #ffb027, #ff8124);
		box-shadow: 0px 3rpx 21rpx 0px rgba(210, 204, 133, 0.6);
		color: #ffffff;
	}

	.labelline {
		background-color: #fff;
		padding: 20rpx 40rpx;
	}

	.labelline text {
		margin-right: 34rpx;
		font-size: 24rpx;
		position: relative;
		padding: 0 0 0 40rpx;
		color: #4c5359;
	}

	.label1::before {
		content: '';
		position: absolute;
		left: 0;
		width: 25rpx;
		top: 4rpx;
		height: 25rpx;
		background: #ff8124;
		border-radius: 2px;
	}

	.label2::before {
		content: '';
		position: absolute;
		left: 0;
		width: 25rpx;
		top: 4rpx;
		height: 25rpx;
		background: #ffffff;
		border: 1rpx solid #ff8124;
		border-radius: 2px;
	}

	.bbfix {
		background: #fff;
		height: 150rpx;
		display: flex;
		position: fixed;
		z-index: 100;
		width: 100%;
		bottom: 0;
		align-items: baseline;
		justify-content: space-between;
		border-top: 1rpx solid #dcdcdc;

		.price {
			padding-left: 20rpx;

			text {
				font-weight: bold;
				font-size: 45rpx;
				color: #ff8124;
			}
		}

		.chooseNum {
			background: #f7f8fa;
			border-radius: 20rpx;
			color: #7b7f83;
			font-size: 24rpx;
			padding: 4rpx 25rpx;
		}

		.subBtn {
			font-size: 36rpx;
			color: #ffffff;
			background: #ff8124;
			height: 120rpx;
			line-height: 100rpx;
			padding: 0 30rpx;
		}
	}

	.ccitemBox {
		padding-bottom: 100rpx;
	}

	.ccitem {
		display: flex;
		align-items: center;
		height: 80rpx;
		margin-bottom: 20rpx;
		justify-content: space-between;
		font-size: 30rpx;
		padding: 0 30rpx;
		border: 1rpx solid #e5e5e5;
		color: #000;
		border-radius: 10rpx;

		icon {
			color: #5a5a5a;
			filter: grayscale(1);
		}
	}

	.calendarLine {
		display: flex;
	}

	.autoHeightBox {
		height: calc(100vh - 230rpx);
		overflow: auto;
	}
</style>
